<template>
    <div class="login-form">
      <div class="toggle">
        <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
          <i class="iconfont icon-user"></i> 使用账号登录
        </a>
        <a @click="isMsgLogin = true" href="javascript:;" v-else>
          <i class="iconfont icon-msg"></i> 使用短信登录
        </a>
      </div>
      <div class="form">
        <my-form autocomplete="off" ref="formCom" :validation-schema="formSchema">
          <template v-if="!isMsgLogin">
            <div class="form-item">
              <div class="input">
                <i class="iconfont icon-user"></i>
                <my-field
                  type="text"
                  name="account"
                  placeholder="请输入账号"
                  v-model="form.account"
                />
              </div>
              <!-- <div class="error"><i class="iconfont icon-warning" />请输入手机号</div> -->
              <ErrorMessage name="account" v-slot="{ message }">
                <div class="error" v-if="message">
                  <i class="iconfont icon-warning" />{{ message }}
                </div>
              </ErrorMessage>
            </div>
            <div class="form-item">
              <div class="input">
                <i class="iconfont icon-lock"></i>
                <my-field
                  type="password"
                  name="password"
                  placeholder="请输入密码"
                  v-model="form.password"
                />
              </div>
              <ErrorMessage name="password" v-slot="{ message }">
                <div class="error" v-if="message">
                  <i class="iconfont icon-warning" />{{ message }}
                </div>
              </ErrorMessage>
            </div>
          </template>
          <template v-else>
            <div class="form-item">
              <div class="input">
                <i class="iconfont icon-user"></i>
                <my-field
                  type="text"
                  name="mobile"
                  placeholder="请输入手机号"
                  v-model="form.mobile"
                />
              </div>
              <ErrorMessage name="mobile" v-slot="{ message }">
                <div class="error" v-if="message">
                  <i class="iconfont icon-warning" />{{ message }}
                </div>
              </ErrorMessage>
            </div>
            <div class="form-item">
              <div class="input">
                <i class="iconfont icon-code"></i>
                <my-field
                  type="text"
                  name="code"
                  placeholder="请输入验证码"
                  v-model="form.code"
                />
                <span class="code" @click="sendFn">{{ time > 0 ? time +'s' : '发送验证码' }}</span>
              </div>
              <ErrorMessage name="code" v-slot="{ message }">
                <div class="error" v-if="message">
                  <i class="iconfont icon-warning" />{{ message }}
                </div>
              </ErrorMessage>
            </div>
          </template>
          <div class="form-item">
            <div class="agree">
              <!-- 自定组件：as XtxCheckbox 指定渲染的组件 -->
              <my-field name="isAgree" as="xtx-checkbox" v-model="form.isAgree" />
              <span>我已同意</span>
              <a href="javascript:;">《隐私条款》</a>
              <span>和</span>
              <a href="javascript:;">《服务条款》</a>
            </div>
            <ErrorMessage name="isAgree" v-slot="{ message }">
              <div class="error" v-if="message">
                <i class="iconfont icon-warning" />{{ message }}
              </div>
            </ErrorMessage>
          </div>
          <a href="javascript:;" class="btn" @click="loginFn">登录</a>
        </my-form>
      </div>

      <div class="action">
        <div class="url">
          <a href="javascript:;">忘记密码</a>
          <a href="javascript:;">免费注册</a>
        </div>
      </div>
    </div>
  </template>
<script>
import { ref, reactive, watch } from 'vue'
import { Form, Field, ErrorMessage } from 'vee-validate'
import schema from '@/utils/schema'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import Message from 'erabbit-ui/packages/components/Message'
import { useIntervalFn } from '@vueuse/core'
import { getCodeMsgAPI, mobileLoginAPI } from '@/api'
export default {
  name: 'LoginForm',
  components: {
    MyForm: Form,
    MyField: Field,
    ErrorMessage
  },
  setup () {
    const router = useRouter()
    const store = useStore()
    const isMsgLogin = ref(false) // 控制账号密码登录/短信验证码登录
    const formCom = ref(null)
    // 表单信息对象
    const form = reactive({
      isAgree: false,
      mobile: 13888888888,
      acc2ount: null,
      password: null,
      code: null
    })
    // 登录按钮
    const loginFn = async () => {
      const res = await formCom.value.validate()
      // 如果表单整体验证通过
      if (res) {
        if (isMsgLogin.value === true) {
          try {
            const { result } = await mobileLoginAPI({
              mobile: form.mobile,
              code: form.code
            })
            console.log(result)
            store.commit('user/SET_Info', result)
            Message({
              type: 'success',
              text: '登陆成功'
            })
            // 登录成功后，合并购物车操作
            await store.dispatch('cart/mergeLocalCartActions')
            store.dispatch('cart/getCartListActions')
            router.replace('/')
          } catch (err) {
            Message({
              type: 'error',
              text: '登陆失败'
            })
          }
        } else {
        // 调用vuex的登录接口
          try {
            await store.dispatch('user/getUserInfoACtions', form)
            Message({
              type: 'success',
              text: '登录成功'
            })
            // 登录成功后，合并购物车操作
            await store.dispatch('cart/mergeLocalCartActions')
            store.dispatch('cart/getCartListActions')
            router.replace('/')
          } catch (err) {
            Message({
              type: 'error',
              text: 'Try Again'
            })
          }
        }
      }
    }
    watch(isMsgLogin, () => {
      // 切换清空表单值
      formCom.value.resetForm()
    })
    // 设置时间
    const time = ref(0)
    // 验证码倒计时
    // isActive 倒计时是否处于激活状态
    const { pause, resume, isActive } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000)
    // 发送验证码
    const sendFn = () => {
      const result = true
      // schema.mobile(form.mobile)
      if (result === true) {
        if (isActive.value === false) {
          time.value = 4
          resume()
          // 获取验证码接口
          getCodeMsgAPI({
            mobile: form.mobile
          }).catch(() => {
            Message({
              type: 'error',
              text: '获取验证码失败'
            })
          })
        }
      } else {
        Message({
          type: 'error',
          text: '请输入正确的手机号'
        })
      }
    }
    // 校验规则
    const { account, password, mobile, code, isAgree } = schema
    const formSchema = { account, password, mobile, code, isAgree }

    return {
      isMsgLogin,
      form,
      formSchema,
      loginFn,
      formCom,
      sendFn,
      time
    }
  }
}
</script>
<style lang="less" scoped>
    // 账号容器
    .login-form {
      .toggle {
        padding: 15px 40px;
        text-align: right;
        a {
          color: var(--xtx-color);
          i {
            font-size: 14px;
          }
        }
      }
      .form {
        padding: 0 40px;
        &-item {
          margin-bottom: 28px;
          .input {
            position: relative;
            height: 36px;
            > i {
              width: 34px;
              height: 34px;
              background: #cfcdcd;
              color: #fff;
              position: absolute;
              left: 1px;
              top: 1px;
              text-align: center;
              line-height: 34px;
              font-size: 18px;
            }
            input {
              padding-left: 44px;
              border: 1px solid #cfcdcd;
              height: 36px;
              line-height: 36px;
              width: 100%;
              &.error {
                border-color: var(--price-color);
              }
              &.active,
              &:focus {
                border-color: var(--xtx-color);
              }
            }
            .code {
              position: absolute;
              right: 1px;
              top: 1px;
              text-align: center;
              line-height: 34px;
              font-size: 14px;
              background: #f5f5f5;
              color: #666;
              width: 90px;
              height: 34px;
              cursor: pointer;
            }
          }
          > .error {
            position: absolute;
            font-size: 12px;
            line-height: 28px;
            color: var(--price-color);
            i {
              font-size: 14px;
              margin-right: 2px;
            }
          }
        }
        .agree {
          a {
            color: #069;
          }
        }
        .btn {
          display: block;
          width: 100%;
          height: 40px;
          color: #fff;
          text-align: center;
          line-height: 40px;
          background: var(--xtx-color);
          &.disabled {
            background: #cfcdcd;
          }
        }
      }
      .action {
        padding: 20px 40px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .url {
          a {
            color: #999;
            margin-left: 10px;
          }
        }
      }
    }
    </style>
